from flask import Flask, request, send_file, jsonify, send_from_directory
from flask_cors import CORS
import os
import uuid
from PIL import Image
import io

app = Flask(__name__)
CORS(app)  # 启用CORS支持

# 配置
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
ADMIN_CREDENTIALS = {'username': 'admin', 'password': 'password'}  # 实际应用中应该使用更安全的认证方式

# 确保上传文件夹存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# 辅助函数
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def generate_thumbnail(image_path, size=(128, 128)):
    with Image.open(image_path) as img:
        img.thumbnail(size)
        thumbnail_path = image_path.replace('uploads', 'thumbnails')
        os.makedirs(os.path.dirname(thumbnail_path), exist_ok=True)
        img.save(thumbnail_path)
        return thumbnail_path

# API路由
@app.route('/api/images/<filename>')
def get_image(filename):
    file_path = os.path.join(UPLOAD_FOLDER, filename)
    if not os.path.exists(file_path):
        return jsonify({'error': 'File not found'}), 404
    return send_file(file_path)

@app.route('/api/thumbnails/<filename>')
def get_thumbnail(filename):
    file_path = os.path.join('thumbnails', filename)
    if not os.path.exists(file_path):
        return jsonify({'error': 'Thumbnail not found'}), 404
    return send_file(file_path)

@app.route('/api/images')
def list_images():
    images = []
    for filename in os.listdir(UPLOAD_FOLDER):
        if allowed_file(filename):
            file_path = os.path.join(UPLOAD_FOLDER, filename)
            thumbnail_filename = os.path.basename(file_path.replace('uploads', 'thumbnails'))
            images.append({
                'filename': filename,
                'url': f"/api/images/{filename}",
                'thumbnail_url': f"/api/thumbnails/{thumbnail_filename}",
                'size': os.path.getsize(file_path)
            })
    return jsonify(images)

@app.route('/api/login', methods=['GET', 'OPTIONS'])
def login():
    # 处理预检请求
    if request.method == 'OPTIONS':
        return {}, 200
    
    auth = request.authorization
    if not auth:
        return jsonify({'error': 'Missing credentials'}), 400

    if auth.username != ADMIN_CREDENTIALS['username'] or auth.password != ADMIN_CREDENTIALS['password']:
        return jsonify({'error': 'Invalid credentials'}), 401

    return jsonify({'message': 'Login successful'})

@app.route('/api/upload', methods=['POST', 'OPTIONS'])
def upload_file():
    # 处理预检请求
    if request.method == 'OPTIONS':
        return {}, 200
    
    # 认证检查
    auth = request.authorization
    if not auth or auth.username != ADMIN_CREDENTIALS['username'] or auth.password != ADMIN_CREDENTIALS['password']:
        return jsonify({'error': 'Unauthorized'}), 401

    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    file = request.files['file']
    
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400

    if file and allowed_file(file.filename):
        # 生成唯一文件名
        file_ext = file.filename.rsplit('.', 1)[1].lower()
        filename = f"{uuid.uuid4()}.{file_ext}"
        file_path = os.path.join(UPLOAD_FOLDER, filename)
        
        # 保存原始文件
        file.save(file_path)
        
        # 生成缩略图
        thumbnail_path = generate_thumbnail(file_path)
        
        return jsonify({
            'filename': filename,
            'url': f"/api/images/{filename}",
            'thumbnail_url': f"/api/thumbnails/{os.path.basename(thumbnail_path)}"
        }), 201

    return jsonify({'error': 'File type not allowed'}), 400

@app.route('/api/images/<filename>', methods=['DELETE', 'OPTIONS'])
def delete_image(filename):
    # 处理预检请求
    if request.method == 'OPTIONS':
        return {}, 200
    
    # 认证检查
    auth = request.authorization
    if not auth or auth.username != ADMIN_CREDENTIALS['username'] or auth.password != ADMIN_CREDENTIALS['password']:
        return jsonify({'error': 'Unauthorized'}), 401

    file_path = os.path.join(UPLOAD_FOLDER, filename)
    thumbnail_path = file_path.replace('uploads', 'thumbnails')
    
    if not os.path.exists(file_path):
        return jsonify({'error': 'File not found'}), 404

    try:
        os.remove(file_path)
        if os.path.exists(thumbnail_path):
            os.remove(thumbnail_path)
        return jsonify({'message': 'File deleted successfully'})
    except Exception as e:
        return jsonify({'error': 'Failed to delete file'}), 500

@app.route('/')
def index():
    return send_file('index.html')

@app.route('/<path:filename>')
def static_files(filename):
    # 确保请求的文件是静态资源（如图片、CSS、JS等）
    if filename.startswith(('images/', 'thumbnails/', 'css/', 'js/')):
        return send_from_directory('.', filename)
    # 对于其他路径，返回index.html以支持前端路由
    return send_file('index.html')

if __name__ == '__main__':
    app.run(debug=True, port=5000)